import { App, Directive } from 'vue';

// 定义权限项的类型
type PermissionItem = {
    permission: string;
};

// 自定义指令的类型定义
const hasPermissionDirective: Directive<HTMLElement, string[]> = {
    mounted(el, binding) {
        // 从 localStorage 中获取权限列表
        const permissionsNameList = localStorage.getItem('permission');
        let permissions: PermissionItem[] = [];
        if (permissionsNameList) {
            try {
                permissions = JSON.parse(permissionsNameList);
            } catch (error) {
                console.error('解析权限列表时出错:', error);
            }
        }
        const value = binding.value;
        // 检查是否有匹配的权限
        const hasMatch = permissions.some(item => {
            return value.includes(item.permission);
        });
        // 如果没有匹配的权限，移除该元素
        if (!hasMatch) {
            const parentNode = el.parentNode;
            if (parentNode) {
                parentNode.removeChild(el);
            }
        }
    },
};

// 定义插件
const hasPermission = {
    install(app: App) {
        // 注册自定义指令
        app.directive('hasPermission', hasPermissionDirective);
    },
};

export default hasPermission;